/*
 * @Author: taoyuqing
 * @Date: 2023-01-09 22:17:16
 * @Description: 登录页
 */
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_svg/svg.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:spree/utils/api.dart';
import 'package:spree/utils/erro_code_enum.dart';
import 'package:spree/utils/resp_code_enum.dart';
import 'package:spree/widgets/common_container.dart';

import '../../provider/model/user_model.dart';

class LoginPage extends StatefulWidget {
  final Function? onLogin;
  LoginPage({Key? key, this.onLogin}) : super(key: key);

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  TextEditingController _pwdCtro = TextEditingController();
  TextEditingController _nameCtro = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('login'),
      ),
      body: CommonContainer(
        child: ListView(
          padding: EdgeInsets.only(top: 100),
          children: [
            SvgPicture.asset(
              'images/BETSPREELOGO.svg',
              width: 200,
            ),
            Container(
              margin: EdgeInsets.only(top: 20),
              padding: EdgeInsets.only(left: 20, right: 20),
              decoration: BoxDecoration(
                  borderRadius: const BorderRadius.all(Radius.circular(8.0)),
                  border: Border.all(
                      width: 1, color: Color.fromRGBO(255, 255, 255, 0.5))),
              child: TextField(
                style: TextStyle(color: Colors.white),
                cursorColor: Colors.white,
                decoration: InputDecoration(
                    icon: Icon(
                      Icons.account_circle_outlined,
                      color: Color.fromRGBO(255, 255, 255, 0.5),
                    ),
                    hintText: 'Enter your Username or Email',
                    border: InputBorder.none,
                    hintStyle: TextStyle(
                      color: Color.fromRGBO(255, 255, 255, 0.7),
                    )),
                controller: _nameCtro,
              ),
            ),
            Container(
              margin: EdgeInsets.only(top: 20),
              padding: EdgeInsets.only(left: 20, right: 20),
              decoration: BoxDecoration(
                  borderRadius: const BorderRadius.all(Radius.circular(8.0)),
                  border: Border.all(
                      width: 1, color: Color.fromRGBO(255, 255, 255, 0.5))),
              child: TextField(
                style: TextStyle(color: Colors.white),
                cursorColor: Colors.white,
                decoration: InputDecoration(
                    suffix: Icon(
                      Icons.remove_red_eye_outlined,
                      color: Color.fromRGBO(255, 255, 255, 0.5),
                    ),
                    icon: Icon(
                      Icons.lock,
                      color: Color.fromRGBO(255, 255, 255, 0.5),
                    ),
                    hintText: 'Enter your password',
                    border: InputBorder.none,
                    hintStyle: TextStyle(
                      color: Color.fromRGBO(255, 255, 255, 0.7),
                    )),
                obscureText: true,
                controller: _pwdCtro,
              ),
            ),
            Container(
              height: 50,
              margin: EdgeInsets.only(top: 20, bottom: 20),
              child: ElevatedButton(
                  style: ButtonStyle(
                    backgroundColor:
                        MaterialStateProperty.all(Color(0xFFF93967)),
                  ),
                  onPressed: () {
                    if (widget.onLogin != null) {
                      widget.onLogin!();
                    }
                    _handleLogin();
                  },
                  child: Text(
                    'Enter',
                    style: TextStyle(fontSize: 16),
                  )),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                TextButton(
                  onPressed: () {
                    Navigator.pushNamed(context, 'RegisterPage');
                  },
                  child: Text(
                    'regist account',
                    style: TextStyle(color: Colors.white),
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(left: 20, right: 20),
                  height: 14,
                  width: 2,
                  color: Color.fromRGBO(255, 255, 255, 0.5),
                ),
                TextButton(
                  onPressed: () {
                    Navigator.pushNamed(context, 'RegisterPage');
                  },
                  child: Text(
                    'forget password',
                    style: TextStyle(color: Colors.white),
                  ),
                )
              ],
            )
          ],
        ),
      ),
    );
  }

  _handleLogin() async {
    if (_nameCtro.text == "") {
      EasyLoading.showError('请输入账号');
      return;
    }
    if (_pwdCtro.text == "") {
      EasyLoading.showError('请输入密码');
      return;
    }
    try {
      dynamic user;
      dynamic userResp = await Api.login(
          {"userName": _nameCtro.text, "passWord": _pwdCtro.text});
      if (userResp['code'] != RespCode.SUCCESS.code) {
        EasyLoading.showError(ErrorCodeMsg.getMsgByCode(userResp['code']));
        return;
      } else {
        user = userResp['data'];
      }
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString('accessToken', user['accessToken']);
      String userId = '';
      if (prefs.get('accessToken') != null && prefs.get('accessToken') != '') {
        dynamic userInfoData = await Api.getInfo();
        dynamic userInfo = userInfoData['data'];
        userId = '${userInfo['userId']}';
        dynamic userAccount = await Api.account();
        Provider.of<UserModel>(context, listen: false).setUserInfo(
            name: '${userInfo['nickname']}',
            id: '${userInfo['userId']}',
            mail: '${userInfo['email']}',
            imgUrl: '${userInfo['avatar']}',
            level: '${userInfo['vipLevel']}',
            token: user['accessToken'],
            amount: '${userAccount['data']['accountAmount']}');
        await prefs.setString('userId', '${userInfoData['data']['userId']}');
        await prefs.setString('userName', _nameCtro.text);
        await prefs.setString('passWord', _pwdCtro.text);
      }

      await EasyLoading.showSuccess(
        'login success',
      );
      Navigator.pop(context, userId);
    } catch (e) {
      print(e);
      EasyLoading.showError('');
    }
  }
}
